<template>
  <div class="app-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <el-page-header :content="websiteId ? `${websiteName} - 云端图片管理` : '云端图片管理'" @back="goBack" />
    </div>

    <!-- 筛选和操作栏 -->
    <div class="filter-container" style="margin-top: 20px;">
      <el-select
        v-model="filterWebsite"
        placeholder="筛选网站"
        clearable
        filterable
        class="filter-item"
        style="width: 180px;"
        @change="handleSearch"
      >
        <el-option label="全部网站" value="" />
        <el-option
          v-for="site in websiteList"
          :key="site.id"
          :label="site.name"
          :value="site.id"
        />
      </el-select>

      <el-input
        v-model="searchKeyword"
        placeholder="搜索文件名"
        prefix-icon="el-icon-search"
        clearable
        class="filter-item"
        style="width: 200px;"
        @clear="handleSearch"
        @keyup.enter.native="handleSearch"
      />

      <el-select
        v-model="filterStatus"
        placeholder="状态筛选"
        clearable
        class="filter-item"
        style="width: 140px;"
        @change="handleSearch"
      >
        <el-option label="全部状态" value="" />
        <el-option label="使用中" value="active" />
        <el-option label="未使用" value="unused" />
        <el-option label="已删除" value="deleted" />
      </el-select>

      <el-select
        v-model="filterSource"
        placeholder="来源筛选"
        clearable
        class="filter-item"
        style="width: 140px;"
        @change="handleSearch"
      >
        <el-option label="全部来源" value="" />
        <el-option label="AI生成" value="ai_generated" />
        <el-option label="用户上传" value="user_uploaded" />
        <el-option label="导入" value="imported" />
        <el-option label="模板" value="template" />
      </el-select>

      <el-select
        v-model="filterType"
        placeholder="类型筛选"
        clearable
        class="filter-item"
        style="width: 140px;"
        @change="handleSearch"
      >
        <el-option label="全部类型" value="" />
        <el-option label="特色图片" value="feature" />
        <el-option label="内容图片" value="content" />
        <el-option label="图标" value="icon" />
        <el-option label="背景图" value="background" />
        <el-option label="Logo" value="logo" />
        <el-option label="横幅" value="banner" />
      </el-select>

      <el-button type="primary" icon="el-icon-search" class="filter-item" @click="handleSearch">
        搜索
      </el-button>
      <el-button
        type="danger"
        icon="el-icon-delete"
        class="filter-item"
        :disabled="selectedImages.length === 0"
        @click="handleBatchDelete"
      >
        批量删除 ({{ selectedImages.length }})
      </el-button>
      <el-button icon="el-icon-refresh" class="filter-item" @click="handleRefresh">
        刷新
      </el-button>
    </div>

    <!-- 图片列表 -->
    <el-card shadow="never" style="margin-top: 20px;">
      <el-table
        v-loading="loading"
        :data="imageList"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />

        <el-table-column label="预览" width="100">
          <template slot-scope="scope">
            <el-image
              :src="scope.row.url"
              :preview-src-list="[scope.row.url]"
              fit="cover"
              style="width: 60px; height: 60px; border-radius: 4px; cursor: pointer;"
            />
          </template>
        </el-table-column>

        <el-table-column label="文件信息" min-width="250" show-overflow-tooltip>
          <template slot-scope="scope">
            <div style="line-height: 1.6;">
              <div style="font-weight: 500; margin-bottom: 4px;">{{ scope.row.filename }}</div>
              <div style="font-size: 12px; color: #909399;">
                <el-tag size="mini" :type="getSourceTagType(scope.row.image_source)">
                  {{ scope.row.image_source_display }}
                </el-tag>
                <el-tag size="mini" type="info" style="margin-left: 5px;">
                  {{ scope.row.image_type_display }}
                </el-tag>
                <div style="margin-top: 4px;">
                  {{ scope.row.dimensions }} · {{ scope.row.file_size_mb }} MB · {{ scope.row.format }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="存储" width="150">
          <template slot-scope="scope">
            <div style="font-size: 12px;">
              <div>{{ scope.row.storage_type_display }}</div>
              <div style="color: #909399; margin-top: 4px;">{{ scope.row.bucket_name }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="使用情况" width="120">
          <template slot-scope="scope">
            <div style="font-size: 12px;">
              <div>引用: {{ scope.row.reference_count }} 次</div>
              <div v-if="scope.row.page_title" style="color: #409EFF; margin-top: 4px;">
                {{ scope.row.page_title }}
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusTagType(scope.row.status)" size="small">
              {{ scope.row.status_display }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" width="160">
          <template slot-scope="scope">
            <div style="font-size: 12px;">
              <div>{{ formatDate(scope.row.created_at) }}</div>
              <div v-if="scope.row.creator_name" style="color: #909399; margin-top: 4px;">
                {{ scope.row.creator_name }}
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="150" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleViewDetail(scope.row)">
              详情
            </el-button>
            <el-button
              type="text"
              size="small"
              style="color: #F56C6C;"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-if="total > 0"
        :current-page="currentPage"
        :page-sizes="[20, 50, 100]"
        :page-size="pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 20px; text-align: right;"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </el-card>

    <!-- 图片详情对话框 -->
    <el-dialog
      title="图片详情"
      :visible.sync="detailDialogVisible"
      width="800px"
    >
      <div v-if="currentImage" style="max-height: 60vh; overflow-y: auto;">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-image
              :src="currentImage.url"
              :preview-src-list="[currentImage.url]"
              fit="contain"
              style="width: 100%; border-radius: 4px; border: 1px solid #DCDFE6;"
            />
          </el-col>
          <el-col :span="12">
            <el-descriptions :column="1" border size="small">
              <el-descriptions-item label="文件名">{{ currentImage.filename }}</el-descriptions-item>
              <el-descriptions-item label="原始文件名">{{ currentImage.original_filename || '-' }}</el-descriptions-item>
              <el-descriptions-item label="存储类型">{{ currentImage.storage_type_display }}</el-descriptions-item>
              <el-descriptions-item label="存储桶">{{ currentImage.bucket_name || '-' }}</el-descriptions-item>
              <el-descriptions-item label="图片来源">{{ currentImage.image_source_display }}</el-descriptions-item>
              <el-descriptions-item label="图片类型">{{ currentImage.image_type_display }}</el-descriptions-item>
              <el-descriptions-item label="文件大小">{{ currentImage.file_size_mb }} MB</el-descriptions-item>
              <el-descriptions-item label="图片尺寸">{{ currentImage.dimensions }}</el-descriptions-item>
              <el-descriptions-item label="格式">{{ currentImage.format }}</el-descriptions-item>
              <el-descriptions-item label="引用次数">{{ currentImage.reference_count }} 次</el-descriptions-item>
              <el-descriptions-item label="状态">
                <el-tag :type="getStatusTagType(currentImage.status)" size="small">
                  {{ currentImage.status_display }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="创建时间">{{ formatDate(currentImage.created_at) }}</el-descriptions-item>
              <el-descriptions-item label="创建人">{{ currentImage.creator ? currentImage.creator.username : '-' }}</el-descriptions-item>
            </el-descriptions>

            <!-- AI信息 -->
            <div v-if="currentImage.image_source === 'ai_generated' && currentImage.ai_prompt" style="margin-top: 20px;">
              <el-divider>AI生成信息</el-divider>
              <el-descriptions :column="1" border size="small">
                <el-descriptions-item label="AI模型">{{ currentImage.ai_model || '-' }}</el-descriptions-item>
                <el-descriptions-item label="图片比例">{{ currentImage.aspect_ratio || '-' }}</el-descriptions-item>
                <el-descriptions-item label="生成提示词">
                  <div style="max-height: 100px; overflow-y: auto; font-size: 12px; line-height: 1.6;">
                    {{ currentImage.ai_prompt }}
                  </div>
                </el-descriptions-item>
              </el-descriptions>
            </div>

            <!-- URL信息 -->
            <div style="margin-top: 20px;">
              <el-divider>URL信息</el-divider>
              <el-form label-width="80px" size="small">
                <el-form-item label="访问URL">
                  <el-input :value="currentImage.url" readonly>
                    <el-button slot="append" icon="el-icon-document-copy" @click="copyToClipboard(currentImage.url)">
                      复制
                    </el-button>
                  </el-input>
                </el-form-item>
                <el-form-item label="本地路径">
                  <el-input :value="currentImage.local_path || '-'" readonly />
                </el-form-item>
                <el-form-item label="对象键">
                  <el-input :value="currentImage.object_key" readonly />
                </el-form-item>
              </el-form>
            </div>
          </el-col>
        </el-row>
      </div>
      <div slot="footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="danger" @click="handleDelete(currentImage)">删除图片</el-button>
      </div>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      title="删除云端图片"
      :visible.sync="deleteDialogVisible"
      width="500px"
    >
      <el-alert type="warning" :closable="false" style="margin-bottom: 15px;">
        <template v-if="deleteFromCloud">
          ⚠️ 将从云存储（OSS/S3）中永久删除图片文件，操作不可恢复！
        </template>
        <template v-else>
          ℹ️ 仅删除数据库记录，云端文件保留（可能产生存储费用）
        </template>
      </el-alert>

      <div style="margin-bottom: 15px;">
        <strong>确认删除以下图片？</strong>
        <div style="margin-top: 10px; max-height: 200px; overflow-y: auto;">
          <ul>
            <li v-for="img in imagesToDelete" :key="img.id" style="margin-bottom: 5px;">
              {{ img.filename }} ({{ img.file_size_mb }} MB)
            </li>
          </ul>
        </div>
      </div>

      <el-form label-width="120px">
        <el-form-item label="删除云端文件">
          <el-switch
            v-model="deleteFromCloud"
            active-text="同时删除"
            inactive-text="仅删除记录"
          />
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" :loading="deleting" @click="confirmDelete">
          确认删除
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getCloudImages, getCloudImageDetail, deleteCloudImages } from '@/api/static_web_cloud_image'
import { Get as getWebsites } from '@/api/static_web/website'

export default {
  name: 'CloudImages',
  data() {
    return {
      websiteId: null,
      websiteName: '',
      websiteList: [],
      filterWebsite: '',
      loading: false,
      imageList: [],
      searchKeyword: '',
      filterStatus: '',
      filterSource: '',
      filterType: '',
      currentPage: 1,
      pageSize: 20,
      total: 0,
      selectedImages: [],
      detailDialogVisible: false,
      currentImage: null,
      deleteDialogVisible: false,
      imagesToDelete: [],
      deleteFromCloud: true,
      deleting: false
    }
  },
  created() {
    // 从 URL 参数获取网站 ID（可选）
    const urlWebsiteId = this.$route.params.websiteId || this.$route.query.website_id

    // 如果有网站ID，设置为筛选条件
    if (urlWebsiteId) {
      this.websiteId = parseInt(urlWebsiteId)
      this.filterWebsite = parseInt(urlWebsiteId)
    }

    // 加载网站列表和图片
    this.fetchWebsiteList()
    this.fetchImages()
  },
  methods: {
    // 加载网站列表
    async fetchWebsiteList() {
      try {
        const response = await getWebsites()
        if (response.success) {
          // API 返回的结构是 {success: true, data: {total: ..., data: [...]}}
          this.websiteList = response.data.data || []

          // 如果有指定网站ID，获取网站名称
          if (this.websiteId) {
            const website = this.websiteList.find(w => w.id === this.websiteId)
            if (website) {
              this.websiteName = website.name
            }
          }
        }
      } catch (error) {
        console.error('获取网站列表失败:', error)
      }
    },

    async fetchImages() {
      this.loading = true
      try {
        const params = {
          status: this.filterStatus,
          image_source: this.filterSource,
          image_type: this.filterType,
          search: this.searchKeyword,
          page: this.currentPage,
          page_size: this.pageSize
        }

        // 如果选择了网站，添加网站ID筛选
        if (this.filterWebsite) {
          params.website_id = this.filterWebsite
        }

        const response = await getCloudImages(params)
        if (response.success) {
          this.imageList = response.data.list
          this.total = response.data.total
        }
      } catch (error) {
        this.$message.error('获取图片列表失败')
        console.error(error)
      } finally {
        this.loading = false
      }
    },

    handleSearch() {
      this.currentPage = 1
      this.fetchImages()
    },

    handleSizeChange(size) {
      this.pageSize = size
      this.currentPage = 1
      this.fetchImages()
    },

    handlePageChange(page) {
      this.currentPage = page
      this.fetchImages()
    },

    handleSelectionChange(selection) {
      this.selectedImages = selection
    },

    async handleViewDetail(row) {
      try {
        const response = await getCloudImageDetail({ image_id: row.id })
        if (response.success) {
          this.currentImage = response.data
          this.detailDialogVisible = true
        }
      } catch (error) {
        this.$message.error('获取图片详情失败')
        console.error(error)
      }
    },

    handleDelete(row) {
      this.imagesToDelete = [row]
      this.deleteFromCloud = true
      this.deleteDialogVisible = true
    },

    handleBatchDelete() {
      if (this.selectedImages.length === 0) {
        this.$message.warning('请先选择要删除的图片')
        return
      }
      this.imagesToDelete = this.selectedImages
      this.deleteFromCloud = true
      this.deleteDialogVisible = true
    },

    async confirmDelete() {
      this.deleting = true
      try {
        const imageIds = this.imagesToDelete.map(img => img.id)
        const response = await deleteCloudImages({
          image_ids: imageIds,
          delete_from_cloud: this.deleteFromCloud
        })

        if (response.success) {
          this.$message.success(response.msg)

          // 显示详细结果
          if (response.data.failed_count > 0) {
            this.$notify({
              title: '删除结果',
              message: `成功: ${response.data.success_count}, 失败: ${response.data.failed_count}`,
              type: 'warning',
              duration: 5000
            })
          }

          this.deleteDialogVisible = false
          this.detailDialogVisible = false
          this.fetchImages()
        } else {
          this.$message.error(response.msg)
        }
      } catch (error) {
        this.$message.error('删除失败')
        console.error(error)
      } finally {
        this.deleting = false
      }
    },

    goBack() {
      this.$router.back()
    },

    getSourceTagType(source) {
      const typeMap = {
        'ai_generated': 'success',
        'user_uploaded': 'primary',
        'imported': 'info',
        'template': 'warning'
      }
      return typeMap[source] || 'info'
    },

    getStatusTagType(status) {
      const typeMap = {
        'active': 'success',
        'unused': 'warning',
        'deleted': 'danger'
      }
      return typeMap[status] || 'info'
    },

    formatDate(dateString) {
      if (!dateString) return '-'
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    },

    copyToClipboard(text) {
      const textarea = document.createElement('textarea')
      textarea.value = text
      document.body.appendChild(textarea)
      textarea.select()
      document.execCommand('copy')
      document.body.removeChild(textarea)
      this.$message.success('已复制到剪贴板')
    }
  }
}
</script>

<style scoped>
.page-header {
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
}

.stat-icon {
  font-size: 40px;
  margin-right: 15px;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  line-height: 1.2;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 4px;
}
</style>
